// import { asyncComponent } from 'react-async-component';
import Taro from "@tarojs/taro";
import {Runtime} from './runtime';
import {Weh5Runtime} from "./weh5Runtime";
import avatar from "../assets/img/icon_79.png";

export const appName = "捷佳车服";
export let currentPlatForm = "h5";
export const companyName = "捷佳车服";
export const ServerHost = "http://ynjcjx.com";
// export const ServerHost = "http://lh.yiboke.net";

//export const ServerHost = "http://192.168.3.154:8016/"; // 林哥电脑
export const ImagePrefix = '';
export const ImageSource = 'web' as 'web' | 'local';
/** 分页初始值 */
export const pageSize = 10;
/** 手机号验证正则 */
export const phoneReg = /^0?(13|14|15|18|17)[\d]{9}$/;
/** 不能以空格开头 */
export const spaceReg = /^[^\s]+/;
/** 不能有中文字符 */
export const zhCNReg = /^[\x00-\xff]*$/;
/** 数字正则 */
export const numberReg = /^[0-9]*$/;
// 字母正则
export const letterReg = /[a-zA-Z]/;
/** 身份证号 */
export const IDCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
// 银行卡号
export const CardReg = /^([1-9]{1})(\d{15}|\d{18})$/;
export const uploadUrl = "/api/services/app/configuration/Upload";
export const dateFormat = "YYYY-MM-DD";
export const dateTimeFormat = "YYYY-MM-DD HH:mm:ss";
export const timeFormat = "HH:mm:ss";
export const timeShortFormat = "HH:mm";
export const termTime = "YYYY.MM.DD";
export const timeFormat1 = "MM月DD日";
export const servicePhoneNumber = "400-847-1688";

export enum userType { '会员' = 1, 'VIP会员', '合伙人' }

export const userSexArr = ['男', '女', '保密']; // 1 = Man , 2 = Women , 3 = UnKnow
export const memberTypeArr = ['会员', 'VIP会员', '合伙人']; // 用户类型
export const huocheId = 3; // 货车ID

export const userTypeObj = [
  {id: 0, title: '普通会员'},
  {id: 1, title: '地区代理'},
  {id: 2, title: '业务员'},
  {id: 3, title: '合伙人'},
];

/**
 * 运行环境
 * @param weapp:微信小程序
 * @param h5:微信公众号
 * @param app:APP
 */

//export const platform: 'weapp' | 'weh5' | 'app' = 'weh5';
export const platform = process.env.TARO_ENV
export const getRuntime = (): Runtime => {
  switch (platform) {
    case 'h5':
      return new Weh5Runtime();
    default:
      return new Runtime();
  }
}

export const partOf = (value?: string, length: number = 18) => {
  value = value || '';
  return value.length <= length ? value : value.substring(0, length) + '...';
}

export const numPartOf = (value?: string,) => {
  var str = value || "";
  return (str.substr(0, 3) + "****" + str.substr(str.length - 4));
}

export const phoneNumPartOf = (value?: string,) => {
  var str = value || "";
  return str.substr(0, 3) + '****' + (str.substr(str.length - 4));
}

export const cardNumPartOf = (value?: string,) => {
  var cardNum = value || "";
  return "*** **** **** **** " + cardNum.substr(-4);
}

// 姓名
export const namePartOf = (value?: string,) => {
  var name = value || "";
  let length = name.length
  if (length === 2) {
    return name.substr(0, 1) + '*'
  } else if (length === 3) {
    return name.substr(0, 1) + '*' + name.substr(length - 1)
  } else {
    return name.substr(0, 1) + '**'
  }
}

export const getUploadResult = (response, callback) => {
  if (response && response.success === true) callback(response.result);
};

export const getFile = (fileName) => {
  switch (ImageSource) {
    case 'local':
      return fileName;
    default:
      return ImagePrefix + fileName.replace(/.*\//, '');
  }
}

export const getAvatar = (src: string) => {
  return src || avatar
}

export const getCaNumber = (val: string) => {
  if (val) {
    return val.substr(0, 2) + ' • ' + val.substr(2)
  }
  return val
}

export const isNumber = (str: string) => {
  let reg = new RegExp(numberReg)
  return reg.test(str)
}

export const isLetter = (str: string) => {
  return new RegExp(letterReg).test(str)
}

export const isPhone = (str: string) => {
  let reg = new RegExp(phoneReg)
  return reg.test(str)
}

export const isIDCard = (str: string) => {
  let reg = new RegExp(IDCardReg)
  return reg.test(str)
}

export const isBankCard = (str: string) => {
  let reg = new RegExp(CardReg)
  return reg.test(str)
}

// 返回几天前或是今天几点几分
export const getSimpleTime = (time: string) => {
  if (!time) return time
  if (time.includes('T')) {
    time = time.replace('T', ' ')
  }
  let nowStamp = new Date().getTime()
  let timeFormat = new Date(time)
  let timeStamp = timeFormat.getTime()
  let interval = nowStamp - timeStamp
  let dayStamp = 1000 * 60 * 60 * 24
  let day = Math.floor(interval / dayStamp)
  let hours = timeFormat.getHours()
  let minute = timeFormat.getMinutes()
  if (day > 0) {
    return `${day}天前`
  } else {
    return `今天${hours}:${minute}`
  }
}


// 根据时间得到几天几时几分几秒前
export const getTime = (time: string) => {
  let [day, hours, minute, seconds] = [0, 0, 0, 0]
  let nowStamp = new Date().getTime();
  let timeStamp = new Date(time).getTime()
  if (nowStamp < timeStamp) {
    return time
  }
  let interval = nowStamp - timeStamp
  let dayStamp = 1000 * 60 * 60 * 24
  day = Math.floor(interval / dayStamp)
  let hoursStamp = interval % dayStamp
  hours = Math.floor(hoursStamp / 1000 / 60 / 60)
  let minuteStamp = hoursStamp % (1000 * 60 * 60)
  minute = Math.floor(minuteStamp / 1000 / 60)
  let secondsStamp = minuteStamp % (1000 * 60)
  seconds = Math.floor(secondsStamp / 1000)
  if (day > 0) {
    return `${day}天${hours}小时${minute}分${seconds}秒前`
  } else if (hours > 0) {
    return `${hours}小时${minute}分${seconds}秒前`
  } else if (minute > 0) {
    return `${minute}分${seconds}秒前`
  } else {
    return `${seconds}秒前`
  }
}

export const subtime = (time: string = '') => {
  time = time ? time : ''
  let pos = time.indexOf('T')
  if (pos !== -1) {
    let temp = time.replace('T', ' ')
    return temp.substr(0, 19)
  } else {
    return time
  }
}

export interface IPage {
  pageIndex: number;
  pageSize: number;
}

/**
 * html文本转纯文本
 * @param HTML html文本
 * @return 纯文本
 * 百度搜来的，好NB的正则啊
 */
export const htmlToText = (HTML) => {
  var input = HTML || '';
  // return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');
  return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, '').replace(/<[^>]+?>/g, '').replace(/\s+/g, ' ').replace(/ /g, ' ').replace(/>/g, ' ');
}

// 配置微信分享
export const getJsApiParam = () => {
  let currentUrl = window.location.href
  let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`
  Taro.showLoading({title: '加载中...'})
  fetch(apiUrl, {
    method: 'GET',
    mode: "cors",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin'
  })
    .then(response => {
      Taro.hideLoading()
      return response.json()
    })
    .then(response => {
      let appId = response.appId
      let timestamp = response.timestamp
      let nonceStr = response.nonceStr
      let signature = response.signature
      this.setState({wxConfig: response})
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: appId, // 必填，公众号的唯一标识
        timestamp: timestamp, // 必填，生成签名的时间戳
        nonceStr: nonceStr, // 必填，生成签名的随机串
        signature: signature,// 必填，签名
        // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
        jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
      });
    })
    .catch(error => {
      console.log(error)
    })
}

export const wxShare = (title: string, desc: string, url: string, imgUrl: string) => {
  // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
  /*let { item } = this.state
  let url1 = ServerHost+'/m/#/pages/dynamic/detail?id='+item.id
  let title = item.title
  let desc = htmlToText(item.content)
  let imgUrl = item.logo*/
  console.log(title)
  console.log(desc)
  var shareData = {
    title,
    desc,
    imgUrl,
    url: url,
    link: url
  };
  wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
    wx.onMenuShareTimeline(shareData);
    wx.updateAppMessageShareData(shareData);
    wx.onMenuShareQQ(shareData);
    wx.onMenuShareWeibo(shareData);
  });
  // WxShare(url,item.logo,item.title,partOf(item.content, 30))
}




